import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index'
//import Login from '@/components/Login'
//import Home from '@/components/Home'
//import TemperatureTrend from '@/components/TemperatureTrend'
//import DistributionMap from '@/components/DistributionMap'
//import UserInfo from '@/components/UserInfo'
//import Report from '@/components/Report'
const Login = () => import('@/components/Login')
const Home = () => import('@/components/Home')
const TemperatureTrend = () => import('@/components/TemperatureTrend')
const DistributionMap = () => import('@/components/DistributionMap')
const UserInfo = () => import('@/components/UserInfo')
const Report = () => import('@/components/Report')

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login,
    },
    {
      path: '/',
      redirect: '/components/TemperatureTrend'
    },
    {
      path: '/components',
      name: 'Home',
      component: Home,
      children: [
        {
          path: '',
          component: TemperatureTrend,
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'TemperatureTrend',
          name: 'TemperatureTrend',
          component: TemperatureTrend,
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'DistributionMap',
          name: 'DistributionMap',
          component: DistributionMap,
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'Report',
          name: 'Report',
          component: Report,
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'UserInfo',
          name: 'UserInfo',
          component: UserInfo,
          meta: {
            requiresAuth: true
          }
        },
      ],
    },
  ]
});

//注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
  //获取store里面的token
  let token = store.state.token;
  //判断要去的路由有没有requiresAuth
  if (to.meta.requiresAuth) {

    if (token) {
      next();
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将刚刚要去的路由path（却无权限）作为参数，方便登录成功后直接跳转到该路由
      });
    }

  } else {
    next(); //如果无需token,那么随它去吧
  }
});
export default router;
